package com.runa.monitor.platinterface.base.async;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;

/**
 * @author zhuj
 */
public class FutureDataTask<T> {

    private Set<AsyncUnit> units = new HashSet<>();

    private BiConsumer process;

    private BiConsumer scavenge;

    private T data;

    private StringBuffer failMessage = new StringBuffer();

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public FutureDataTask(BiConsumer process, BiConsumer scavenge, T data) {
        this.process = process;
        this.scavenge = scavenge;
        this.data = data;
    }

    public void addUnit(AsyncUnit unit) {
        units.add(unit);
    }

    public void successCall(AsyncUnit unit) {
        process.accept(data, unit.get(AsyncUnit.AsyncState.Correct));
    }

    public synchronized void failCall(AsyncUnit unit, String failMessage) {
        scavenge.accept(data, unit.get(AsyncUnit.AsyncState.Error));
        this.failMessage.append(failMessage);
    }

    public T getData() {
        lock.lock();
        try {
            condition.await();
            return data;
        } catch (InterruptedException e) {
            
        } finally {
            lock.unlock();
        }
        return null;
    }

    public String getFailMessage() {
        return failMessage.toString();
    }

    public void reset() {
        try {
            units.clear();
            failMessage.setLength(0);
        } catch (Exception e) {
            units = new HashSet<>();
        }
    }

}
